package controller

import (
	"gobase/app/model"
	"gobase/app/service"
	"gobase/util"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

//用户控制器
type UserController struct {
	BaseController
}

//用户服务层
var userSrv *service.UserService

//路由注册
func (ctl *UserController) Router(router *gin.Engine) {
	r := router.Group("admin/user")
	r.GET("/list", ctl.queryList)
	r.GET("/add", ctl.add)
	r.POST("/add", ctl.add)
	r.GET("/apply/:id", ctl.apply)
	r.POST("/apply/:id", ctl.apply)

	r.GET("/edit/:id", ctl.edit)
	r.PUT("/edit/:id", ctl.edit)
	r.GET("/detail/:id", ctl.detail)

	r.DELETE("/del/:id", ctl.del)

	//启用/禁用
	r.PATCH("/eord/:id/:state", ctl.enableOrDisable)
}

//列表
func (ctl *UserController) queryList(c *gin.Context) {
	userSrv = service.NewUserService(c)
	var p = util.GetPageParam(c)
	var qusername = c.DefaultQuery("qusername", "")
	var qorgid = c.DefaultQuery("qorgid", "")

	orgOptionList := util.GetOrgOptionsTree("0", service.NewOrgService(c).GetNoDisableList())
	resultp, userList := userSrv.QueryList(p, qusername, qorgid)
	c.HTML(http.StatusOK, "user/list.html", gin.H{
		"title":         "用户列表",
		"qusername":     qusername,
		"qorgid":        qorgid,
		"_page":         resultp,
		"dataList":      userList,
		"flashmsg":      ctl.GetSessionFlash(c),
		"orgOptionList": orgOptionList,
	})
}

//新增
func (ctl *UserController) add(c *gin.Context) {
	if ctl.IsPost(c.Request.Method) {
		var message = ""
		var status = false
		roleIds, _ := c.GetPostFormArray("roleids[]")

		user := new(model.User)
		err := c.ShouldBind(user)
		if err != nil {
			message = util.GetValidMsg(err, model.User{})
			util.GetLog(c).Error(err)
			ctl.ResponseJSON(c, status, message)
		}

		userSrv = service.NewUserService(c)
		err = userSrv.Add(user, roleIds)
		if err != nil {
			util.GetLog(c).Error(err)
			message = err.Error()
		} else {
			status = true
		}
		ctl.ResponseJSON(c, status, message)
	} else {
		orgOptionList := util.GetOrgOptionsTree("0", service.NewOrgService(c).GetNoDisableList())
		c.HTML(http.StatusOK, "user/add.html", gin.H{
			"title":         "添加用户",
			"orgOptionList": orgOptionList,
			"roleList":      service.NewRoleUserService(c).GetRolesByUid(0),
		})
	}
}

//编辑
func (ctl *UserController) edit(c *gin.Context) {
	idStr := c.Param("id")
	id, _ := strconv.Atoi(idStr)
	userSrv = service.NewUserService(c)

	if ctl.IsPut(c.Request.Method) {
		var message = ""
		var status = false

		user := new(model.User)
		err := c.ShouldBind(user)
		if err != nil {
			message = util.GetValidMsg(err, model.User{})
			util.GetLog(c).Error(err)
			ctl.ResponseJSON(c, status, message)
		}

		err = userSrv.Update(int64(id), user)
		if err != nil {
			util.GetLog(c).Error(err)
			message = err.Error()
		} else {
			status = true
		}
		ctl.ResponseJSON(c, status, message)
	} else {
		//查询用户信息
		userInfo, _ := userSrv.GetByID(int64(id))
		orgOptionList := util.GetOrgOptionsTree("0", service.NewOrgService(c).GetNoDisableList())
		c.HTML(http.StatusOK, "user/edit.html", gin.H{
			"title":         "修改用户",
			"user":          userInfo,
			"orgOptionList": orgOptionList,
		})
	}
}

//详情
func (ctl *UserController) detail(c *gin.Context) {
	idStr := c.Param("id")
	id, _ := strconv.Atoi(idStr)
	userSrv = service.NewUserService(c)
	userInfo, _ := userSrv.GetMapByID(int64(id))

	c.HTML(http.StatusOK, "user/detail.html", gin.H{
		"title":    "用户详情",
		"user":     userInfo,
		"roleList": service.NewRoleUserService(c).GetRolesByUid(int64(id)),
	})
}

//删除
func (ctl *UserController) del(c *gin.Context) {
	var message = "删除失败:"
	var status = false

	idStr := c.Param("id")
	if idStr == "" {
		message += "参数为空!"
		ctl.ResponseJSON(c, status, message)
	}

	id, _ := strconv.Atoi(idStr)
	userSrv = service.NewUserService(c)
	err := userSrv.DeleteById(int64(id))
	if err != nil {
		util.GetLog(c).Error(err)
		ctl.ResponseJSON(c, status, err.Error())
	} else {
		status = true
	}
	ctl.ResponseJSON(c, status, message)
}

//分配角色
func (ctl *UserController) apply(c *gin.Context) {
	idStr := c.Param("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)

	if ctl.IsPost(c.Request.Method) {
		roleIds, _ := c.GetPostFormArray("roleids[]")
		err := service.NewUserService(c).AddRoleForUser(id, roleIds)
		if err != nil {
			ctl.ResponseJSON(c, false, err.Error())
		}
		ctl.ResponseJSON(c, true, "")
	} else {
		userInfo, _ := service.NewUserService(c).GetByID(id)
		c.HTML(http.StatusOK, "user/apply.html", gin.H{
			"title":    "分配角色",
			"user":     userInfo,
			"roleList": service.NewRoleUserService(c).GetRolesByUid(id),
		})
	}
}

//启用/禁用
func (ctl *UserController) enableOrDisable(c *gin.Context) {
	var message = "更新状态失败:"
	var status = false

	idStr := c.Param("id")
	stateStr := c.Param("state")
	if idStr == "" || stateStr == "" || (stateStr != "1" && stateStr != "0") {
		message += "参数错误!"
		ctl.ResponseJSON(c, status, message)
	}

	id, _ := strconv.Atoi(idStr)
	userSrv = service.NewUserService(c)
	err := userSrv.EnableOrDisable(int64(id), stateStr)
	if err != nil {
		util.GetLog(c).Error(err)
		message = err.Error()
	} else {
		status = true
	}
	ctl.ResponseJSON(c, status, message)
}
